﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Group.aspx.cs" Inherits="CRMWeb.Pages.Admin.Group" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
</head>
<body>
    <table id="dgGroup" title="All Groups" style="width: auto; height:650px" autorowheight="true" 
        toolbar="#toolbarGroup" rownumbers="true" fitcolumns="true" singleselect="true"  >
        <thead>
            <tr>
                <th field="GroupID" hidden="true">GroupID</th>
                <th field="ParentGroupID" hidden="true">ParentGroupID</th>
                <th field="GroupName" width="150">Group Name</th>
                <th field="GroupType" width="80">Group Type</th>
                <th field="Description" width="400" data-options="formatter:formatedescription">Description</th>
            </tr>
        </thead>
    </table>
    <div id="toolbarGroup">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" plain="true" onclick="newGroup()">New</a>
        <a id="alnkeditGroup" href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-edit" plain="true" onclick="editGroup()">Edit</a>
        <a id="alnkdeleteGroup" href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-remove" plain="true" onclick="deleteGroup()">Delete</a>
    </div>
    <div id="dlgGroupCriteria" title="Group" class="easyui-dialog" style="width: 1180px; height: 500px; padding: 0px;" closed="true">
        <div>
            <div class="ftitle">Group Information</div>
            <div style="float: left; width: 89%;">
                <div id="divGroupMsg"></div>
                <div class="fitem" id="master_detail">
                    <label>Group Name:</label>
                    <input id="txtGroupName" class="easyui-validatebox" />
                    <label>Parent Group</label>
                    <input id="cmbParentGroup" class="easyui-combobox" name="FieldName1" editable="false" style="width: 240px;" data-options="panelHeight:'300'" />
                </div>
                <div class="fitem">
                    <label>Type:</label>
                    <select id="cmbType" class="easyui-combobox" editable="false" data-options="panelHeight:'auto'" name="Type" style="width: 100px;">
                        <option value="Application">Application</option>
                        <option value="Client">Client</option>
                    </select>
                    <label>Field Name:</label>
                    <input id="ddlFieldName" class="easyui-combobox" editable="false" name="FieldName" style="width: 240px;"
                        data-options="panelHeight:'300',url:'/WebServices/SMSTemplate.ashx?method=getColumnName1',
				            valueField:'field_name',
				            textField:'COLUMN_NAME',
                            onSelect: function(){
                         setValueControl($('#ddlFieldName').combobox('getValue'), '');
                        }" />
                    <input id="hdnfieldtype" type="hidden" />
                    <label>Operator:</label>
                    <select id="cmbOperator" class="easyui-combobox" editable="false" data-options="panelHeight:'auto'" name="Operator" style="width: 100px;">
                        <option value=""></option>
                        <option value="=">Equals</option>
                        <option value=" like ">Contains</option>
                        <option value=" not like ">Not Contains</option>
                        <option value="<">Less than</option>
                        <option value=">">Greater than</option>
                    </select>
                    <label>Value:</label>
                    <input id="txtFieldValue" class="easyui-validatebox" />
                    <input id="txtNumberValue" class="easyui-numberbox" />
                    <span id="divddlValue">
                        <input id="cmbValue" class="easyui-combobox" name="FieldName1" style="width: 240px;" data-options="panelHeight:'300'" />
                    </span>
                    <span id="spnDateValue">
                        <input id="txtDateValue" type="text" class="easyui-datebox" data-options="formatter:DefaultformaDate,onSelect: function () {
                                var temp = $('#txtDateValue').datebox('getValue');
                                var date_arr = temp.split('/');
                                var calObj = $('#txtDateValue').datebox('calendar');
                                calObj.calendar('moveTo', new Date(date_arr[2], date_arr[1] - 1, date_arr[0]));
                         }" />
                    </span>
                    <span id="spnPurposeSummary">
                        <select id="cmbPurposeSummary" class="easyui-combobox" editable="false" data-options="panelHeight:'auto'" name="PurposeSummary" style="width: 100px;">
                            <option value="Personal">Personal</option>
                            <option value="Bussiness">Bussiness</option>
                        </select>
                    </span>
                    <span id="spnOperator">
                        <label id="lblAndOr">And/Or:</label>
                        <select id="cmbAndOr" class="easyui-combobox" editable="false" data-options="panelHeight:'auto'" name="Action" style="width: 80px;">
                            <option value=""></option>
                            <option value="And">And</option>
                            <option value="OR">Or</option>
                        </select>
                    </span>
                    <input id="hdnGroupID" type="hidden" />
                </div>
                <div style="height: 10px"></div>
                <div class="fitem">
                    <table id="dgGroupCriteria" autorowheight="true" toolbar="#tbGroupCriteria" pagination="true" data-options="pageSize:10"
                        rownumbers="true" singleselect="true">
                        <thead>
                            <tr>
                                <th field="blank1" width="5">(</th>
                                <th field="GroupType" width="120">Type</th>
                                <th field="FieldName" width="300">Field Name</th>
                                <th field="Operator" width="80" align="center">Operator</th>
                                <th field="FieldValue" width="200" align="center" data-options="formatter:formateValue">Value</th>
                                <th field="blank2" width="5">)</th>
                                <th field="AndOr" width="100">AndOr</th>
                            </tr>
                        </thead>
                    </table>
                    <div class="fitem" style="text-align: right">
                        <a href="#" class="easyui-linkbutton" onclick="SaveData()">Save</a>
                        <a href="#" class="easyui-linkbutton" onclick="ResetPage()">Cancel </a>
                        <br />
                    </div>
                    <div class="fitem" id="divpreviewApp" style="display: none">
                        <table id="dgGroupDataApp" title="Preview Data - Application" style="width: auto;" autorowheight="true" fitcolumns="true"
                            rownumbers="true" singleselect="true" data-options="pagination:true,pageSize:20">
                            <thead>
                                <tr>
                                    <th field="app_id" width="30" sortable="true">Application No  </th>
                                    <th field="applicant1" width="40" sortable="true">First Applicant  </th>
                                    <th field="SecondApplicant" width="40" sortable="true">Second Applicant  </th>
                                    <th field="DesiredAmount" width="30" sortable="true">Desired Amount </th>
                                    <th field="app_result" width="70" sortable="true">Last Result   </th>
                                    <th field="CreatedDate" width="30" sortable="true" data-options="formatter:formatDate">Create Date  </th>
                                    <th field="EditDate" width="30" sortable="true" data-options="formatter:formatDate">Edit Date   </th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                    <div class="fitem" id="divpreviewClient" style="display: none">
                        <table id="dgGroupDataClient" title="Preview Data - Client" style="width: auto;" autorowheight="true" fitcolumns="true"
                            rownumbers="true" singleselect="true" data-options="pagination:true,pageSize:20">
                            <thead>
                                <tr>
                                    <th field="ContactID" width="50" sortable="true">Client No  </th>
                                    <th field="ClientName" width="80" sortable="true">Full Name  </th>
                                    <th field="DateBirth" width="50" data-options="formatter:formatDate" sortable="true">Birth Date  </th>
                                    <th field="State" width="30" sortable="true">State</th>
                                    <th field="client_CreateDate" width="30" data-options="formatter:formatDate" sortable="true">Create Date  </th>
                                    <th field="client_EditDate" width="30" data-options="formatter:formatDate" sortable="true">Edit Date  </th>

                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
            <div style="float: right; padding-right: 5px; width: 10%">
                <a id="lnkaddTolist" href="#" class="easyui-linkbutton" style="width: 81px" onclick="addToList()">Add to list</a><br />
                <a id="lnkEditList" href="#" class="easyui-linkbutton" style="width: 81px; margin-top: 5px" onclick="editList()">Edit</a><br />
                <a href="#" class="easyui-linkbutton" style="width: 81px; margin-top: 5px" onclick="removeList()">Remove</a><br />
                <a href="#" class="easyui-linkbutton" style="width: 81px; margin-top: 5px" onclick="removeAllList()">Remove All</a>
                <a href="#" class="easyui-linkbutton" style="width: 81px; margin-top: 5px" onclick="previewData()">Preview</a>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#cmbParentGroup').combobox('textbox').bind('click', function () {
                $('#cmbParentGroup').combobox('showPanel');
            });
            $('#cmbType').combobox('textbox').bind('click', function () {
                $('#cmbType').combobox('showPanel');
            });
            $('#ddlFieldName').combobox('textbox').bind('click', function () {
                $('#ddlFieldName').combobox('showPanel');
            });
            $('#cmbOperator').combobox('textbox').bind('click', function () {
                $('#cmbOperator').combobox('showPanel');
            });
            $('#cmbOperator').combobox('textbox').bind('click', function () {
                $('#cmbOperator').combobox('showPanel');
            });
            $('#cmbValue').combobox('textbox').bind('click', function () {
                $('#cmbValue').combobox('showPanel');
            });

            $('#dgGroup').datagrid({
                url: '/WebServices/Group/Group.ashx?method=GetGroupList',
                onDblClickRow: function () {
                    var rows = $('#dgGroup').datagrid('getSelected');
                    if (rows.GroupName != 'Root' && rows.GroupName != 'Process' && rows.GroupName != 'Priority Queue') {
                        editGroup();
                    }
                },
                onClickRow: function () {
                    var rows = $('#dgGroup').datagrid('getSelected');
                    if (rows.GroupName == 'Root' || rows.GroupName == 'Process' || rows.GroupName == 'Priority Queue') {
                        $('#alnkeditGroup').linkbutton('disable');
                        $('#alnkdeleteGroup').linkbutton('disable');
                    }
                    else {
                        $('#alnkeditGroup').linkbutton('enable');
                        $('#alnkdeleteGroup').linkbutton('enable');
                    }
                }
            });

            $('#dgGroupCriteria').datagrid({
                onDblClickRow: function () {
                    editList();
                }
            });


        });

        function IsValidate() {
            var strMsg = '';
            var flag = true;
            if ($('#txtGroupName').val() == '')
                strMsg += '<label style="color:red;">Group Name is required</label><br/>';
            $('#divGroupMsg').html(strMsg);
            if (strMsg == '')
                flag = true;
            else
                flag = false;

            return flag;
        }
        function ResetPage() {
            $('#dlgGroupCriteria').dialog('close');
            $('#dgGroupCriteria').datagrid('loadData', { "total": 0, "rows": [] });
            if (isAppdata == 1)
                $('#dgGroupDataApp').datagrid('loadData', { "total": 0, "rows": [] });
            if (isClientData == 1)
                $('#dgGroupDataClient').datagrid('loadData', { "total": 0, "rows": [] });

        }
        function SaveData() {
            if (IsValidate()) {

                var GroupTypeValue = $('#cmbType').combobox('getValue');
                var whereCondition = '';
                var GroupName1 = '';

                if ($('#txtGroupName').val() != 'Root' && $('#txtGroupName').val() != 'Process' && $('#txtGroupName').val() != 'Priority Queue') {
                    GroupName1 = $('#txtGroupName').val();
                }
                else {
                    $.messager.alert('Morgan CRM', 'GroupName can not Root, Process or Priority Queue');
                    return;
                }
                var Description = prepareQuery();
                if ($('#hdnGroupID').val() == '') {
                    $.ajax({
                        url: '/WebServices/Group/Group.ashx?method=AddGroup',
                        contentType: "application/json; charset=utf-8",
                        data: { ParentGroupID: $('#cmbParentGroup').combobox('getValue'), GroupName: GroupName1, GroupType: GroupTypeValue, Description: Description },
                        success: function (data) {
                            $('#dgGroup').datagrid('reload');
                            $.messager.alert('Morgan CRM', 'Group added Successfully');
                            ResetPage();
                        }
                    });
                }
                else {
                    $.ajax({
                        url: '/WebServices/Group/Group.ashx?method=EditGroup',
                        contentType: "application/json; charset=utf-8",
                        data: { GroupID: $('#hdnGroupID').val(), ParentGroupID: $('#cmbParentGroup').combobox('getValue'), GroupName: GroupName1, GroupType: GroupTypeValue, Description: Description },
                        success: function (data) {
                            $('#dgGroup').datagrid('reload');
                            $.messager.alert('Morgan CRM', 'Group edited Successfully');
                            ResetPage();

                        }
                    });
                }
            }
        }

        window.onresize = function () {
            $('#dgGroup').datagrid('resize', {
                width: window.innerWidth,
                height: window.innerHeight
            });
        }
        function formatDate(value, row) {
            var date = null;
            if (value == null)
                date = new Date();
            else
                date = new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var month = '';
            switch (m) {
                case 1:
                    month = 'Jan';
                    break;
                case 2:
                    month = 'Feb';
                    break;
                case 3:
                    month = 'Mar';
                    break;
                case 4:
                    month = 'Apr';
                    break;
                case 5:
                    month = 'May';
                    break;
                case 6:
                    month = 'Jun';
                    break;
                case 7:
                    month = 'Jul';
                    break;
                case 8:
                    month = 'Aug';
                    break;
                case 9:
                    month = 'Sep';
                    break;
                case 10:
                    month = 'Oct';
                    break;
                case 11:
                    month = 'Nov';
                    break;
                case 12:
                    month = 'Dec';
                    break;
            }
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + ' ' + month + ' ' + y;
        }
        function formatedescription(value, row) {
            var str = new String(value);
            str = str.substring(35);
            str = str.replace(/=/gi, ' equals to ');
            str = str.replace(/like/gi, ' contains ');
            str = str.replace(/not like/gi, ' not contains ');
            str = str.replace(/%/gi, '');
            str = str.replace(/>/gi, ' greater than ');
            str = str.replace(/</gi, ' less than ');
            return str;
        }
        var isAppdata;
        var isClientData;

        function previewData() {
            isAppdata = 0;
            isClientData = 0;
            if ($('#cmbType').combobox('getValue') == 'Application') {
                $('#divpreviewApp').show();
                $('#divpreviewClient').hide();
                $('#dgGroupDataApp').datagrid({
                    url: '/WebServices/Group/Group.ashx?method=GetGroupDataFromQuery&Type=Application&Description=' + encodeURIComponent(prepareQuery())
                });
                isAppdata = 1;

            }
            else if ($('#cmbType').combobox('getValue') == 'Client') {

                $('#divpreviewApp').hide();
                $('#divpreviewClient').show();
                $('#dgGroupDataClient').datagrid({
                    url: '/WebServices/Group/Group.ashx?method=GetGroupDataFromQuery&Type=Client&Description=' + encodeURIComponent(prepareQuery())
                });
                isClientData = 1;
            }
        }

        function formateValue(value, row) {
            value = value.replace(/%/gi, '');
            return value;
        }
        function addToList() {

            var cmbType = $('#cmbType').combobox('getValue');
            var ddlFieldName = $('#ddlFieldName').combobox('getValue');
            var ddlFieldText = $('#ddlFieldName').combobox('getText');
            var cmbOperator = $('#cmbOperator').combobox('getValue');
            var cmbAndOr = $('#cmbAndOr').combobox('getValue');
            var txtValue;
            var fieldType = $('#hdnfieldtype').val();
            if (ddlFieldName == 'EditDate')
                fieldType = 'date';
            else if (ddlFieldName == 'PurposeSummary')
                fieldType = 'PurposeSummary';
            if (ddlFieldName == 'CreateDate' || ddlFieldName == 'EditDate' || ddlFieldName == 'deletedFlag' || ddlFieldName == 'Memo') {
                if (ddlFieldText == 'CreateDate (Client)' || ddlFieldText == 'EditDate (Client)' || ddlFieldText == 'deletedFlag (Client)' || ddlFieldText == 'Memo (Client)')
                    ddlFieldName = "client_" + ddlFieldName;
                else if (ddlFieldText == 'CreateDate (Loan)' || ddlFieldText == 'EditDate (Loan)' || ddlFieldText == 'deletedFlag (Loan)' || ddlFieldText == 'Memo (Loan)')
                    ddlFieldName = "loan_" + ddlFieldName;
            }

            if (fieldType == 'varchar' || fieldType == 'text')
                txtValue = $('#txtFieldValue').val();
            else if (fieldType == 'date' || fieldType == 'datetime' || fieldType == 'DateBirth') {
                txtValue = ConvertSystemDate($('#txtDateValue').datebox('getValue'));
            }
            else if (fieldType == 'int' || fieldType == 'bigint' || fieldType == 'tinyint' || fieldType == 'bool')
                txtValue = $('#txtNumberValue').numberbox('getValue');
            else if (fieldType == 'app_result') {
                txtValue = $('#cmbValue').combobox('getValue');
            }
            else if (fieldType == 'PurposeSummary')
                txtValue = $('#cmbPurposeSummary').combobox('getValue');

            var rows = $('#dgGroupCriteria').datagrid('getRows');

            if (rows.length > 0)
                $('#cmbType').combobox('disable');
            else
                $('#cmbType').combobox('enable');

            if (rows.length == 0) {
                if (cmbType != '' && ddlFieldName != '' && cmbOperator != '') {
                    $('#dgGroupCriteria').datagrid('appendRow', {
                        blank1: '', GroupType: cmbType, FieldName: ddlFieldName, Operator: cmbOperator, FieldValue: txtValue, AndOr: '', blank2: ''
                    });
                    $('#cmbType').combobox('disable');
                    $('#cmbOperator').combobox('setValue', '');
                    $('#cmbAndOr').combobox('setValue', '');
                    $('#ddlFieldName').combobox('setValue', '');
                    $('#cmbValue').combobox('setValue', '');
                    $('#txtFieldValue').val('');
                    $('#txtDateValue').datebox('setValue', '');
                    $('#txtNumberValue').numberbox('setValue', '');
                    $('#spnOperator').show();
                }
            }
            else {
                if (cmbType != '' && ddlFieldName != '' && cmbOperator != '' && cmbAndOr != '') {
                    $('#dgGroupCriteria').datagrid('appendRow', {
                        blank1: '', GroupType: cmbType, FieldName: ddlFieldName, Operator: cmbOperator, FieldValue: txtValue, AndOr: cmbAndOr, blank2: ''
                    });
                    //$('#cmbType').combobox('setValue', '');
                    $('#cmbOperator').combobox('setValue', '');
                    $('#cmbAndOr').combobox('setValue', '');
                    $('#ddlFieldName').combobox('setValue', '');
                    $('#cmbValue').combobox('setValue', '');
                    $('#txtFieldValue').val('');
                    $('#txtDateValue').datebox('setValue', '');
                    $('#txtNumberValue').numberbox('setValue', '');
                }
            }
        }

        function editList() {
            $('#lnkEditList').focus();
            var row = $('#dgGroupCriteria').datagrid('getSelected');
            if (row) {
                if ($('#lnkEditList').html() == '<span class="l-btn-left"><span class="l-btn-text l-btn-focus">Save</span></span>') {
                    var cmbType = $('#cmbType').combobox('getValue');
                    var ddlFieldName = $('#ddlFieldName').combobox('getValue');
                    var ddlFieldText = $('#ddlFieldName').combobox('getText');
                    var cmbOperator = $('#cmbOperator').combobox('getValue');
                    var cmbAndOr = $('#cmbAndOr').combobox('getValue');
                    var fieldType = $('#hdnfieldtype').val();
                    if (ddlFieldName == 'EditDate')
                        fieldType = 'date';
                    else if (ddlFieldName == 'PurposeSummary')
                        fieldType = 'PurposeSummary';

                    if (ddlFieldName == 'CreateDate' || ddlFieldName == 'EditDate' || ddlFieldName == 'deletedFlag' || ddlFieldName == 'Memo') {
                        if (ddlFieldText == 'CreateDate (Client)' || ddlFieldText == 'EditDate (Client)' || ddlFieldText == 'deletedFlag (Client)' || ddlFieldText == 'Memo (Client)')
                            ddlFieldName = "client_" + ddlFieldName;
                        else if (ddlFieldText == 'CreateDate (Loan)' || ddlFieldText == 'EditDate (Loan)' || ddlFieldText == 'deletedFlag (Loan)' || ddlFieldText == 'Memo (Loan)')
                            ddlFieldName = "loan_" + ddlFieldName;
                    }
                    var txtValue;
                    if (fieldType == 'varchar' || fieldType == 'text')
                        txtValue = $('#txtFieldValue').val();
                    else if (fieldType == 'date' || fieldType == 'datetime') {
                        txtValue = ConvertSystemDate($('#txtDateValue').datebox('getValue'));
                    }
                    else if (fieldType == 'int' || fieldType == 'bigint' || fieldType == 'tinyint' || fieldType == 'bool')
                        txtValue = $('#txtNumberValue').numberbox('getValue');
                    else if (fieldType == 'app_result')
                        txtValue = $('#cmbValue').combobox('getValue');
                    else if (fieldType == 'PurposeSummary')
                        txtValue = $('#cmbPurposeSummary').combobox('getValue');

                    var rows = $('#dgGroupCriteria').datagrid('getRows');

                    if (rows.length == 1) {
                        if (cmbType != '' && ddlFieldName != '' && cmbOperator != '') {
                            var indx = $('#dgGroupCriteria').datagrid('getRowIndex', row);
                            $('#dgGroupCriteria').datagrid('updateRow', {
                                index: indx, row: {
                                    blank1: '', GroupType: cmbType, FieldName: ddlFieldName, Operator: cmbOperator, FieldValue: txtValue, AndOr: ' ', blank2: ''
                                }
                            });

                            $('#cmbOperator').combobox('setValue', '');
                            $('#cmbAndOr').combobox('setValue', '');
                            $('#ddlFieldName').combobox('setValue', '');
                            $('#cmbValue').combobox('setValue', '');
                            $('#txtFieldValue').val('');
                            $('#txtDateValue').datebox('setValue', '');
                            $('#txtNumberValue').numberbox('setValue', '');
                            $('#spnOperator').show();
                            $('#divpreviewApp').hide();
                            $('#divpreviewClient').hide();
                        }
                    }
                    else {
                        if (cmbType != '' && ddlFieldName != '' && cmbOperator != '' && cmbAndOr != '') {
                            var indx = $('#dgGroupCriteria').datagrid('getRowIndex', row);
                            $('#dgGroupCriteria').datagrid('updateRow', {
                                index: indx, row: {
                                    blank1: '', GroupType: cmbType, FieldName: ddlFieldName, Operator: cmbOperator, FieldValue: txtValue, AndOr: cmbAndOr, blank2: ''
                                }
                            });

                            $('#cmbOperator').combobox('setValue', '');
                            $('#cmbAndOr').combobox('setValue', '');
                            $('#ddlFieldName').combobox('setValue', '');
                            $('#cmbValue').combobox('setValue', '');
                            $('#txtFieldValue').val('');
                            $('#txtDateValue').datebox('setValue', '');
                            $('#txtNumberValue').numberbox('setValue', '');
                        }
                    }
                    $('#lnkEditList').html('<span class="l-btn-left"><span class="l-btn-text">Edit</span></span>');
                    $('#lnkaddTolist').linkbutton('enable');
                }
                else {
                    $('#cmbType').combobox('setValue', row.GroupType);
                    $('#cmbOperator').combobox('setValue', row.Operator);
                    $('#cmbAndOr').combobox('setValue', row.AndOr);
                    var field = row.FieldName;
                    field = field.replace('client_', '');
                    field = field.replace('loan_', '');
                    $('#ddlFieldName').combobox('setValue', field);
                    setValueControl(field, row.FieldValue);

                    var rows = $('#dgGroupCriteria').datagrid('getRows');
                    if (rows.length == 1)
                        $('#spnOperator').hide();
                    else
                        $('#spnOperator').show();
                    $('#lnkaddTolist').linkbutton('disable');
                    $('#lnkEditList').html('<span class="l-btn-left"><span class="l-btn-text">Save</span></span>');
                }
            }
        }

        function setValueControl(ddlFieldName, value) {
            value = formateValue(value, '');
            if (ddlFieldName == 'EditDate') {
                setDateBoxValue(value);
                $('#spnDateValue').show();
                $('#spnPurposeSummary').hide();
                $('#txtFieldValue').hide();
                $('#txtNumberValue').hide();
                $('#divddlValue').hide();
            }
            else if (ddlFieldName == 'app_result') {
                $('#spnDateValue').hide();
                $('#txtFieldValue').hide();
                $('#spnPurposeSummary').hide();
                $('#txtNumberValue').hide();
                $('#divddlValue').show();
                $('#hdnfieldtype').val(ddlFieldName);
                $('#cmbValue').combobox({
                    url: '/WebServices/Group/Group.ashx?method=Get_crm_LastResult',
                    valueField: 'ResultDescription',
                    textField: 'ResultDescription'
                });
                $('#cmbValue').combobox('setValue', value);
            }
            else if (ddlFieldName == 'PurposeSummary') {
                $('#spnDateValue').hide();
                $('#spnPurposeSummary').hide();
                $('#txtFieldValue').hide();
                $('#txtNumberValue').hide();
                $('#divddlValue').hide();
                $('#spnPurposeSummary').show();
                $('#cmbPurposeSummary').combobox('setValue', value);
            }
            else {
                $.ajax({
                    url: '/WebServices/Group/Group.ashx?method=GetFieldtype',
                    contentType: 'application/json; charset=utf-8',
                    data: { 'fieldName': ddlFieldName },
                    success: function (response) {
                        $('#hdnfieldtype').val(response);
                        if ((response == 'varchar') || (response == 'text')) {
                            $('#txtFieldValue').show();
                            $('#txtFieldValue').val(value);
                            $('#txtNumberValue').hide();
                            $('#spnDateValue').hide();
                            $('#divddlValue').hide();
                            $('#spnPurposeSummary').hide();
                        }
                        else if ((response == 'int') || (response == 'bigint') || (response == 'decimal') || (response == 'tinyint')) {
                            $('#txtNumberValue').show();
                            $('#txtNumberValue').val(value);
                            $('#spnDateValue').hide();
                            $('#txtFieldValue').hide();
                            $('#divddlValue').hide();
                            $('#spnPurposeSummary').hide();
                        }
                        else if ((response == 'date') || (response == 'datetime')) {
                            if (value == '0001-01-01T00:00:00' || value == null || value == '') {
                                $('#txtDateValue').datebox('setValue', value);
                            }
                            else {
                                setDateBoxValue(value);
                            }
                            $('#spnDateValue').show();
                            $('#txtFieldValue').hide();
                            $('#txtNumberValue').hide();
                            $('#divddlValue').hide();
                            $('#spnPurposeSummary').hide();
                        }
                    }
                });
            }
        }

        function removeList() {
            var row = $('#dgGroupCriteria').datagrid('getSelected');
            if (row) {
                var index = $('#dgGroupCriteria').datagrid('getRowIndex', row);
                $('#dgGroupCriteria').datagrid('deleteRow', index);
                var rows = $('#dgGroupCriteria').datagrid('getRows');
                if (row.length > 0)
                    $('#cmbType').combobox('disable');
                if (rows.length == 0) {
                    $('#spnOperator').hide();
                    $('#divpreviewApp').hide();
                    $('#divpreviewClient').hide();
                    $('#txtFieldValue').hide();
                    $('#txtNumberValue').hide();
                    $('#divddlValue').hide();
                    $('#spnDateValue').hide();
                }
            }
        }
        function removeAllList() {
            $('#dgGroupCriteria').datagrid('loadData', { "total": 0, "rows": [] });
            $('#spnOperator').hide();
            $('#cmbType').combobox('enable');
            $('#divpreviewApp').hide();
            $('#divpreviewClient').hide();
            $('#txtFieldValue').hide();
            $('#txtNumberValue').hide();
            $('#divddlValue').hide();
            $('#spnDateValue').hide();
        }

        function DefaultformaDate(value) {
            var date = new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
        }
        function ConvertSystemDate(value) {
            dArr = value.split('/');
            return dArr[2] + '-' + dArr[1] + '-' + dArr[0];
        }

        function setDateBoxValue(value) {
            if (value == '0001-01-01T00:00:00' || value == null || value == '')
                return '';
            else {
                dArr = value.split('-');
                var dateVal = dArr[2] + '/' + dArr[1] + '/' + dArr[0];
                var date_arr = dateVal.split('/');
                $('#txtDateValue').datebox('setValue', dateVal);
                var calObj = $('#txtDateValue').datebox('calendar');
                calObj.calendar('moveTo', new Date(date_arr[2], date_arr[1] - 1, date_arr[0]));

            }
        }

        function prepareQuery() {
            var GroupTypeValue = $('#cmbType').combobox('getValue');
            var whereCondition = '';
            var rows = $('#dgGroupCriteria').datagrid('getRows');
            for (var index = 0; index < rows.length; index++) {
                GroupTypeValue = rows[index].GroupType;
                //For where Condition
                if (index != 0)
                    whereCondition = whereCondition + ' ' + rows[index].AndOr + ' ';
                else
                    whereCondition = 'where ';
                if ((rows[index].Operator == '<' || rows[index].Operator == '>') && (rows[index].FieldName == 'CreatedDate' || rows[index].FieldName == 'EditDate' || rows[index].FieldName == 'DateBirth' || rows[index].FieldName == 'CreateDate' || rows[index].FieldName == 'client_CreateDate' || rows[index].FieldName == 'client_EditDate')) {
                    whereCondition = whereCondition + rows[index].FieldName + rows[index].Operator + '\'' + rows[index].FieldValue + ' 23:59:59\'';
                }
                else if (rows[index].FieldName == 'app_result') {


                    if (rows[index].Operator == '=' || rows[index].Operator == ' like ' || rows[index].Operator == ' not like ') {

                        if (rows[index].Operator == ' like ' || rows[index].Operator == '=')
                            whereCondition += "app_result='" + $.trim(rows[index].FieldValue) + "'";

                        else if (rows[index].Operator == ' not like ')

                            whereCondition += "app_result<>'" + $.trim(rows[index].FieldValue) + "'";

                    }
                }
                else {
                    if (rows[index].Operator == '=' || rows[index].Operator == ' like ' || rows[index].Operator == ' not like ') {
                        if (rows[index].Operator == ' like ') {
                            whereCondition = whereCondition + rows[index].FieldName + rows[index].Operator + '\'' + rows[index].FieldValue + '%\'';
                        }
                        else if (rows[index].Operator == ' not like ') {
                            whereCondition = whereCondition + rows[index].FieldName + rows[index].Operator + '\'' + rows[index].FieldValue + '%\'';
                        }
                        else {
                            whereCondition = whereCondition + rows[index].FieldName + rows[index].Operator + '\'' + rows[index].FieldValue + '\'';
                        }
                    }
                    else
                        whereCondition = whereCondition + rows[index].FieldName + rows[index].Operator + rows[index].FieldValue;
                }
            }
            var query = 'Select * From view_groupdata ' + whereCondition;
            return query;
        }

        function newGroup() {
            //clear data
            $('#hdnGroupID').val('');
            $('#divpreviewApp').hide();
            $('#divpreviewClient').hide();

            $('#txtFieldValue').hide();
            $('#txtNumberValue').hide();
            $('#divddlValue').hide();
            $('#spnDateValue').hide();
            $('#lnkaddTolist').linkbutton('enable');
            $('#cmbType').combobox('enable');
            $('#dlgGroupCriteria').dialog('open');
            $('#spnOperator').hide();
            $('#txtGroupName').val('');
            $('#cmbParentGroup').combobox('setValue', '');
            $('#cmbType').combobox('setValue', 'Application');
            //$('#ddlFieldName').combobox({ url: '/WebServices/SMSTemplate.ashx?method=getColumnName1' });
            $('#cmbOperator').combobox('setValue', '');
            $('#cmbAndOr').combobox('setValue', '');
            $('#ddlFieldName').combobox('setValue', '');
            $('#cmbValue').combobox('setValue', '');
            $('#txtFieldValue').val('');

            $('#cmbParentGroup').combobox({
                url: '/WebServices/Group/Group.ashx?method=GetParentGroupList',
                valueField: 'GroupID',
                textField: 'GroupName'
            });

            $('#dgGroupCriteria').datagrid('loadData', { "total": 0, "rows": [] });

            //$('#dgGroupDataApp').datagrid('loadData', { "total": 0, "rows": [] });
            //$('#dgGroupDataClient').datagrid('loadData', { "total": 0, "rows": [] });
            $('#lnkEditList').html('<span class="l-btn-left"><span class="l-btn-text">Edit</span></span>');
        }

        function editGroup() {
            var row = $('#dgGroup').datagrid('getSelected');
            if (row) {

                //clear data
                $('#dlgGroupCriteria').dialog('open');
                $('#spnOperator').hide();

                $('#divpreviewApp').hide();
                $('#divpreviewClient').hide();

                $('#txtFieldValue').hide();
                $('#txtNumberValue').hide();
                $('#divddlValue').hide();
                $('#spnDateValue').hide();
                $('#txtGroupName').val('');
                $('#cmbParentGroup').combobox('setValue', '');
                //$('#cmbType').combobox('setValue', '');
                $('#cmbOperator').combobox('setValue', '');
                $('#cmbAndOr').combobox('setValue', '');
                $('#ddlFieldName').combobox('setValue', '');
                $('#cmbValue').combobox('setValue', '');
                $('#txtFieldValue').val('');
                $('#txtDateValue').datebox('setValue', '');
                $('#txtNumberValue').numberbox('setValue', '');

                $('#cmbParentGroup').combobox({
                    url: '/WebServices/Group/Group.ashx?method=GetParentGroupList',
                    valueField: 'GroupID',
                    textField: 'GroupName'
                });

                $('#dgGroupCriteria').datagrid('loadData', { "total": 0, "rows": [] });

                //set edit records
                $('#hdnGroupID').val(row.GroupID);
                $('#txtGroupName').val(row.GroupName);
                $('#cmbType').combobox('setValue', row.GroupType);
                $('#cmbParentGroup').combobox('setValue', row.ParentGroupID);

                // $('#ddlFieldName').combobox('reload', '/WebServices/SMSTemplate.ashx?method=getColumnName1');
                $('#lnkEditList').html('<span class="l-btn-left"><span class="l-btn-text">Edit</span></span>');

                //display description
                var Description = row.Description;
                
                Description = Description.replace(/%/gi, '');
                
                var matches = Description.match(/\'(.*?)\'/g);
                for (var index = 0; index < matches.length; index++) {
                    var repstr = matches[index].split(' ').join('#');
                    Description = Description.replace(matches[index], repstr);
                }
                var sptDescription = Description.split(' ');
                for (var index = 0; index < sptDescription.length; index++) {
                    if (sptDescription[index].indexOf('=') >= 0) {
                        var sptEquals = sptDescription[index].split('=');
                        var AndOrText = '';
                        if (sptDescription[index - 1] == 'where')
                            AndOrText = ' ';
                        else
                            AndOrText = sptDescription[index - 1];
                        $('#dgGroupCriteria').datagrid('appendRow', {
                            blank1: '', GroupType: row.GroupType, FieldName: sptEquals[0], Operator: '=', FieldValue: sptEquals[1].replace(/'/g, '').split('#').join(' '), AndOr: AndOrText, blank2: ''
                        });
                    }
                    else if (sptDescription[index] == 'not' && sptDescription[index + 1] == 'like') {
                        var AndOrText = '';
                        if (sptDescription[index - 2] == 'where')
                            AndOrText = ' ';
                        else
                            AndOrText = sptDescription[index - 2];
                        $('#dgGroupCriteria').datagrid('appendRow', {
                            blank1: '', GroupType: row.GroupType, FieldName: sptDescription[index - 1], Operator: ' not like ', FieldValue: sptDescription[index + 2].replace(/'/g, '').split('#').join(' '), AndOr: AndOrText, blank2: ''
                        });
                        return;
                    }
                    else if (sptDescription[index] == 'like') {
                        var AndOrText = '';
                        if (sptDescription[index - 2] == 'where')
                            AndOrText = ' ';
                        else
                            AndOrText = sptDescription[index - 2];
                        $('#dgGroupCriteria').datagrid('appendRow', {
                            blank1: '', GroupType: row.GroupType, FieldName: sptDescription[index - 1], Operator: ' like ', FieldValue: sptDescription[index + 1].replace(/'/g, '').split('#').join(' '), AndOr: AndOrText, blank2: ''
                        });
                    }
                    else if (sptDescription[index].indexOf('<') >= 0) {
                        sptDescription[index] = sptDescription[index].replace('#23:59:59', '');
                        var sptEquals = sptDescription[index].split('<');
                        var AndOrText = '';
                        if (sptDescription[index - 1] == 'where')
                            AndOrText = ' ';
                        else
                            AndOrText = sptDescription[index - 1];
                        $('#dgGroupCriteria').datagrid('appendRow', {
                            blank1: '', GroupType: row.GroupType, FieldName: sptEquals[0], Operator: '<', FieldValue: sptEquals[1].replace(/'/g, '').split('#').join(' '), AndOr: AndOrText, blank2: ''
                        });
                    }
                    else if (sptDescription[index].indexOf('>') >= 0) {
                        sptDescription[index] = sptDescription[index].replace('#23:59:59', '');
                        var sptEquals = sptDescription[index].split('>');
                        var AndOrText = '';
                        if (sptDescription[index - 1] == 'where')
                            AndOrText = ' ';
                        else
                            AndOrText = sptDescription[index - 1];
                        $('#dgGroupCriteria').datagrid('appendRow', {
                            blank1: '', GroupType: row.GroupType, FieldName: sptEquals[0], Operator: '>', FieldValue: sptEquals[1].replace(/'/g, '').split('#').join(' '), AndOr: AndOrText, blank2: ''
                        });
                    }
                }
                $('#spnOperator').show();
                var rows = $('#dgGroupCriteria').datagrid('getRows');
                if (rows.length > 0)
                    $('#cmbType').combobox('disable');
                else
                    $('#cmbType').combobox('enable');
            }
        }
        function deleteGroup() {
            var row = $('#dgGroup').datagrid('getSelected');
            if (row) {
                $.messager.confirm('Delete Group', 'Are you sure delete this group ?', function (r) {
                    if (r) {
                        $.ajax({
                            url: '/WebServices/Group/Group.ashx?method=CheckParentGroup',
                            contentType: "application/json; charset=utf-8",
                            data: { 'GroupID': row.GroupID, 'GroupName': row.GroupName, 'ParentGroupID': row.ParentGroupID },
                            success: function (data) {
                                if (data == '0') {
                                    $.ajax({
                                        url: '/WebServices/Group/Group.ashx?method=DeleteGroup',
                                        contentType: "application/json; charset=utf-8",
                                        data: { 'GroupID': row.GroupID },
                                        success: function () {
                                            $('#dgGroup').datagrid('reload');
                                            $.messager.alert('Morgan CRM', 'Group Deleted Successfully');
                                        }
                                    });
                                }
                                else {
                                    $.messager.alert('Morgan CRM', 'Root or Parent Group can not Deleted');
                                }

                            }
                        });
                    }
                });
            }
        }
    </script>
</body>
</html>
